package com.lianjia.analysis.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理所有未捕获的异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Map<String, Object>> handleException(Exception e) {
        logger.error("未捕获异常: ", e);
        
        Map<String, Object> errorInfo = new HashMap<>();
        errorInfo.put("success", false);
        errorInfo.put("message", "系统内部错误");
        errorInfo.put("error", e.getMessage());
        
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorInfo);
    }
    
    /**
     * 处理数据访问异常
     */
    @ExceptionHandler(org.springframework.dao.DataAccessException.class)
    public ResponseEntity<Map<String, Object>> handleDataAccessException(Exception e) {
        logger.error("数据访问异常: ", e);
        
        Map<String, Object> errorInfo = new HashMap<>();
        errorInfo.put("success", false);
        errorInfo.put("message", "数据库访问错误");
        errorInfo.put("error", e.getMessage());
        
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorInfo);
    }
    
    /**
     * 处理业务逻辑异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<Map<String, Object>> handleIllegalArgumentException(IllegalArgumentException e) {
        logger.error("参数错误: ", e);
        
        Map<String, Object> errorInfo = new HashMap<>();
        errorInfo.put("success", false);
        errorInfo.put("message", "参数错误");
        errorInfo.put("error", e.getMessage());
        
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorInfo);
    }
    
    /**
     * 处理资源不存在异常
     */
    @ExceptionHandler(org.springframework.web.server.ResponseStatusException.class)
    public ResponseEntity<Map<String, Object>> handleResponseStatusException(org.springframework.web.server.ResponseStatusException e) {
        logger.error("HTTP状态异常: ", e);
        
        Map<String, Object> errorInfo = new HashMap<>();
        errorInfo.put("success", false);
        errorInfo.put("message", e.getReason());
        errorInfo.put("error", e.getMessage());
        
        return ResponseEntity.status(e.getStatusCode()).body(errorInfo);
    }
} 